//
//  UIButton+Block.m
//  HYSmileiOS
//
//  Created by alekye on 16/4/24.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "UIButton+Block.h"
#import <objc/runtime.h>

#define kButtonBlockKey @"ButtonBlockKey"

@implementation UIButton (Block)

/**
 *  UIButton添加UIControlEvents事件的block
 *
 *  @param event 事件
 *  @param action block代码
 */
- (void) handleControlEvent:(UIControlEvents)event withBlock:(ButtonActionBlock)action {
    objc_setAssociatedObject(self, kButtonBlockKey, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}

/**
 *  按钮点击事件
 *
 *  @param sender 按钮
 */
- (void)callActionBlock:(UIButton*)sender {
    ButtonActionBlock block = (ButtonActionBlock)objc_getAssociatedObject(self, kButtonBlockKey);
    if (block) {
        block(sender);
    }
}

@end
